package handlers

import (
	"category-list/cache"
	"category-list/models"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Detail(c *gin.Context) {
	id := c.Query("id")
	var app []models.App
	redis_key := "detail_" + id
	cach, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cach == "" {
		models.DB.Where("id=?", id).First(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cach), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
	return
}
func List(c *gin.Context) {
	var app []models.App
	redis_key := "list"
	cach, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cach == "" {
		models.DB.Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cach), &app)
	}
	var total int64
	models.DB.Model(&models.App{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  app,
		"total": total,
	})
	return
}
func Add(c *gin.Context) {
	name := c.PostForm("name")
	num, _ := strconv.Atoi(c.PostForm("num"))
	typ := c.PostForm("typ")
	if name == "" || num == 0 || typ == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.App{
		Model: gorm.Model{},
		Name:  name,
		Num:   num,
		Typ:   typ,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	var app models.App
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	models.DB.Where("id=?", data.ID).First(&app)
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
